/**********************************************************************
 * LeechCraft - modular cross-platform feature rich internet client.
 * Copyright (C) 2006-2014  Georg Rudoy
 *
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
 **********************************************************************/

#pragma once
#include "findnotification.h"
#include <QtWebEngineCore/QWebEnginePage>
#include <QtWebEngineWidgets/QWebEngineView>
#include <QtWebEngineCore/QWebEngineFindTextResult>

namespace SailmiPIM::Util
{
	/** @brief A helper class to aid connecting FindNotification with
	 * QtWebEngine.
	 *
	 * This class is basically a FindNotification providing an utility
	 * function ToPageFlags() to convert FindNotification::FindFlags to
	 * QWebEnginePage::FindFlags.
	 *
	 * FindNotificationWE takes care of all the search-related things
	 * and automatically handles the QWebView passed to its constructor
	 * in its handleNext() implementation. So, using this class is as
	 * simple as just instantiating an object, passing the needed
	 * QWebView instance to its constructor.
	 *
	 * @ingroup GuiUtil
	 */
	class UTIL_GUI_API FindNotificationWE : public FindNotification
	{
		QWebEngineView * const WebView_;
		QString PreviousFindText_;
	public:
		/** @brief Constructs the find notification using the given
		 * proxy and near widget.
		 *
		 * @param[in] proxy The core proxy to be used by this find
		 * notification.
		 * @param[in] near The web view near which to embed.
		 *
         * @sa FindNotificationWE
		 */
        FindNotificationWE(const ICoreProxy_ptr& proxy, QWebEngineView *near);

        ~FindNotificationWE() override;

        void HandleNext (const QString& text, FindFlags findFlags) override;

        void Reject () override;

        /** @brief Converts the given \em findFlags to WebKit find flags.
		 *
		 * @param[in] findFlags The find flags in terms of
		 * FindNotification.
		 * @return The find flags in terms of WebKit.
		 */
        static QWebEnginePage::FindFlags ToPageFlags (FindNotification::FindFlags findFlags)
        {
            QWebEnginePage::FindFlags pageFlags;
            auto check = [&pageFlags, findFlags] (FindNotification::FindFlag ourFlag, QWebEnginePage::FindFlag pageFlag)
            {
                if (findFlags & ourFlag)
                    pageFlags |= pageFlag;
            };
            check (FindNotification::FindCaseSensitively, QWebEnginePage::FindCaseSensitively);
            check (FindNotification::FindBackwards, QWebEnginePage::FindBackward);
            return pageFlags;
        }

    private:
        void ClearFindResults ();
	};
}
